const express = require('express');
const app = express();
const session = require('express-session');
const server = require('http').createServer(app);
const bodyParser = require('body-parser');
const userDao = require('./dao/userDao');
const md5 = require('./tools/md5');
const mongoose = require('mongoose');
const formidable=require('formidable');
const timestamp=require('time-stamp');
const path=require('path');
const fs=require('fs');
const io=require('socket.io').listen(server);
/**
 *  中间件
 */
app.use(express.static(__dirname + '/src'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(session({
	secret:'ding',
	resave:false,
	saveUninitialized:true
}))


/**
 *  登录
 */
app.post('/login',function(req,res){
	console.log('--------------login--------------');
	var user=req.body.user;
	var pass=req.body.pass;
	console.log('param:'+user+"/"+pass);
	userDao.find({'username':user,'password':pass},{},function(data){
		if(data.length>0){
			//存入session
			req.session.user=data[0];
		}
		res.send(data);
	})
})

/**
 *  注册
 */
app.post('/register',function(req,res){
	var username=req.body.username;
	var password=req.body.password;
	var mobile=req.body.mobile;
	var nickName=req.body.nickname;
	console.log('--------------register--------------');
	userDao.insert({username,password,nickName,mobile},function(data){
		if(data && data.id){
			res.send('success');
		}else{
			res.send('fail');
		}
	});
});

/**
 *  初始页面
 */
app.get('/', function(req, res) {
	console.log('--------------main.html--------------');
	res.sendFile(__dirname + '/src/main.html');
})

/**
 *  头像上传
 */
app.post('/photoUpload',function(req,res){
	console.log('--------------photoUpload--------------');
	let user=req.session.user;
	if(!user){
		res.send("no-login");
		return;
	}

	var form = new formidable.IncomingForm();
	form.uploadDir='./src/photos';
	form.parse(req,function(err,fields,files){
		//定义时间戳格式
		var ttt = timestamp('YYYYMMDDHHmmss');
		//产生一个五位随机数
		var ran = parseInt(Math.random()*89999+10000);
		//获取后缀名
		var extname = path.extname(files.myfile.name);
		//旧地址
		var oldPath = __dirname+'/'+files.myfile.path;
		//新地址
		var newPath = __dirname+'/src/photos/'+ttt+ran+extname;
		fs.rename(oldPath,newPath,function(err){
			if(err){
				console.error("ername error:"+err);
			}
		})
		userDao.update({_id:user._id},{$set:{photo:'/photos/'+ttt+ran+extname}},function(result){
			req.session.user.photo='/photos/'+ttt+ran+extname;
			res.send(req.session.user);
		})
	})
})

/**
 * 查询好友列表
 */
app.get('/friends', function(req, res) {
	console.log('--------------friends--------------');
	let id=req.query._id;
	let user=req.session.user;
	if(!user){
		res.send("no-login");
		return;
	}
	//组装查询结构(对ID进行数据类型转换)
	user.friends.map(function(value,index){
		return mongoose.Types.ObjectId(value);
	})
 	userDao.find({'_id':{$in:user.friends}},null,function(data){
		res.send(data);
	})
})

/**
 *  查询聊天消息
 */
app.get('/news',function(req,res){
	console.log('--------------news--------------');
	res.send('success');
})

//在线列表
const ONLINE_USERS={};
//离线消息列表
const OFFLINE_MESSAGE=[];
/**
 *  连接成功
 */
io.sockets.on('connection',function(socket){

	/**
	 *  登入(页面自动执行此操作)
	 */
	socket.on('sign',function(user){
		console.log('online_user_count:'+ONLINE_USERS);
		//登记用户ID
		socket.userid=user._id;
		//加入在线列表
		ONLINE_USERS[socket.userid]=socket;
		//读取离线消息,将自己未读的消息全部导出发送,发送过的消息从原列表中删除
		let arr=[];//初始值一定要给
		// arr=OFFLINE_MESSAGE.filter(function(value){
		// 	return value.to==user._id;
		// })
		for(let i=0;i<OFFLINE_MESSAGE.length;i++){
			let value=OFFLINE_MESSAGE[i];
			if(value.to==user._id){
				arr.push(value);
				OFFLINE_MESSAGE.splice(i,1);
			}
		}
		io.to(socket.id).emit('STC',arr);
	})

	/**
	 * 接收消息
	 */
	socket.on('CTS',function(obj){
		console.log('online_user_count:'+ONLINE_USERS);
		console.log('CTS:');
		let to=ONLINE_USERS[obj.friend];
		if(!to){
			console.log('friend offline.');
			//如果对方不在线，就存储到离线列表中
			OFFLINE_MESSAGE.push({
				from:socket.userid,
				to:obj.friend,
				message:obj.message
			})
		}else{
			console.log('friend online : '+obj.message);
			//发送给指定的接收人
			io.to(to.id).emit('STC',[
				{
					friend:socket.userid,
					message:obj.message
				}
			]);
		}
	})


	/**
	 *  离线
	 */
	socket.on('disconnect',function(){
		console.log(socket.userid+'已退出');
		delete ONLINE_USERS[socket.userid];//移出在线列表
	})
})


server.listen(9000);
console.log('server listening 9000')